package Server.controller;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.RepertoryDao;
import Server.dao.ShopSpecDao;
import Server.entity.Repertory;
import Server.entity.ShopClass;
import Server.entity.ShopSpec;
import Server.tool.BeanToJson;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("RepertoryController")
public class RepertoryController {
    @Autowired
    private RepertoryDao repertoryDao;
    @Autowired
    private ShopSpecDao shopSpecDao;
    @RequestMapping("List")
    public RetResult ClassList(@RequestBody JSONObject jsonObject){
        Repertory entity = (Repertory) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), Repertory.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("shopSpec.shop.name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("shopSpec.name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Repertory> example = Example.of(entity,matcher);
        Page<Repertory> userlist = repertoryDao.findAll(example,pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    @OperLog("出入库")
    @RequestMapping("Save")
    public RetResult Save(@RequestBody JSONObject jsonObject){
        JSONArray jsonArray = jsonObject.getJSONArray("spec");
        for (Object obj : jsonArray) {
            JSONObject jso = (JSONObject) obj;
            ShopSpec spec = (ShopSpec) BeanToJson.jsonTobean(jso.toString(), ShopSpec.class);
            if(spec.getRepertory()!=0){
                ShopSpec entity =shopSpecDao.findByUuid(spec.getUuid());
                if(entity.getRepertory()+spec.getRepertory()<0){
                    return RetResponse.makeErrRsp("库存不能为负");
                }
                entity.setRepertory(entity.getRepertory()+spec.getRepertory());
                shopSpecDao.save(entity);
                Repertory repertory = new Repertory();
                repertory.setShopSpec(entity);
                repertory.setNumber(spec.getRepertory());
                repertoryDao.save(repertory);
            }else{
                continue;
            }
        }
        return RetResponse.makeOKRsp();
    }
}
